package com.woniu.service.impl;

import com.woniu.dao.BillManagerDao;
import com.woniu.entity.BillList;
import com.woniu.service.BillManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class BillManagerServiceImpl implements BillManagerService {
    @Autowired
    BillManagerDao billManagerDao;

    @Override
    public List<BillList> findAllBill(BillList billList) {
        Calendar instance = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<BillList> allBill = billManagerDao.findAllBill(billList);
        for (BillList bill : allBill) {
            if(Objects.nonNull(bill.getCollectionId())){
                bill.setCollectionName(billManagerDao.findCollectionName(bill.getCollectionId()));
            }
            Date creditTime = bill.getCreditTime();
            instance.setTime(creditTime);
            int year = instance.get(Calendar.YEAR);
            int month = instance.get(Calendar.MONTH)+1;
            int day = instance.get(Calendar.DAY_OF_MONTH);
            int hour = instance.get(Calendar.HOUR_OF_DAY);
            int minute = instance.get(Calendar.MINUTE);
            int second = instance.get(Calendar.SECOND);
            Integer periods = bill.getPeriods();
            String newTime = null;
            if( month+periods<=12 ){
                newTime = year+"-"+(month+periods)+"-"+day+" "+hour+":"+minute+":"+second;
            }else {
                newTime = (year+(month+periods)/12)+"-"+(month+(month+periods)%12)+"-"+day+" "+hour+":"+minute+":"+second;
            }
            Date date = null;
            try {
                date = format.parse(newTime);

            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            bill.setEssentialPayDeadline(date);
        }
        return allBill;
    }

    @Override
    public boolean addClientRemark(BillList billList) {
        return billManagerDao.addClientRemark(billList);
    }
}
